package service

import (
	"context"

	"gitee.com/WisdomClassroom/collectingData/glb"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
)

func (s *Service) UploadAnswers(ctx context.Context, req *pb.Answers) (*pb.ResponseStatus, error) {
	token := core.NewToken()
	err := token.UnpackToken(req.GetAuthToken(), &core.FlagTokenCert)
	if err != nil {
		return &pb.ResponseStatus{
			Code: pb.ResponseStatusCode_NotAuth, Error: err.Error(),
		}, nil
	}

	answers := make([]interface{}, 0, len(req.GetAnswers()))
	for _, answer := range req.GetAnswers() {
		answers = append(answers, models.Answer{
			UserUUID:     token.UUID,
			StartTime:    answer.GetStartTime(),
			EndTime:      answer.GetEndTime(),
			QuestionUUID: answer.GetQuestionUUID(),
			IsA:          answer.GetIsA(),
			IsB:          answer.GetIsB(),
			IsC:          answer.GetIsC(),
			IsD:          answer.GetIsD(),
			IsTrue:       answer.GetIsTrue(),
		})
	}

	_, err = glb.AnswerCollection.InsertMany(ctx, answers)
	if err != nil {
		glb.Logger.Error(err.Error())
		return &pb.ResponseStatus{Code: pb.ResponseStatusCode_ServerError}, nil
	}
	return &pb.ResponseStatus{Code: pb.ResponseStatusCode_Suc}, nil
}
